package com.iot.mqttbroker.controller;

import com.iot.mqttbroker.config.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: zhych
 * @title: WebSocketServer
 * @projectName: mqtt-broker
 * @date: 2022/11/9 22:01
 * @menu:
 * @description: -
 */
@Slf4j
@Component
@ServerEndpoint(value = "/info/{userId}")
public class WebSocketServer {


    private static final ConcurrentHashMap<String, Session> webSocketMap = new ConcurrentHashMap<>();

    private static String userId = null;

    @OnOpen
    public String onOpen(Session session, @PathParam("userId") String userId) throws IOException {
        WebSocketServer.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, session);
            //加入set中
        } else {
            webSocketMap.put(userId, session);
        }
        log.info("客户端：{}连接成功", session.getId());
        this.sendMessage();
        return "success";
    }

    @OnClose
    public void onClose(Session session) {
        log.info("客户端：{}连接断开", session.getId());

    }

    @OnError
    public void onError(Session session, Throwable t) {
        log.info("【websocket消息】出现未知错误 ");
        t.printStackTrace();
    }

    @OnMessage
    public String onMsg(String message, Session session) throws IOException {
        log.info("从客户端：{} 收到<--:{}", session.getId(), message);
        String send = message.toUpperCase();
        String result = "客户：%s您好，来自server 的消息:%s";
        RedisTemplate<String, String> redisTemplate = SpringContextHolder.getBean("redisTemplate");
        Object led = redisTemplate.opsForValue().get("led");
        if (Objects.isNull(led)) {
            message = "1";
        } else {
            message = led.toString();
        }
        log.info(String.format(result, session.getId(), send));
        session.getBasicRemote().sendText(message);
        return send;
    }

    public void sendMessage(String message) throws IOException {
        Session session = webSocketMap.get(userId);
        onMsg(message, session);
    }

    public void sendMessage() throws IOException {
        Session session = webSocketMap.get(userId);
        onMsg("", session);
    }
}
